package xyz.ylx.apirotation.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import xyz.ylx.apirotation.service.AIModelService;
import xyz.ylx.apirotation.common.constants.ApiConstants;
import xyz.ylx.apirotation.exception.custom.ApiKeyException;

import java.util.Map;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class OpenAIServiceImpl implements AIModelService {

    private final WebClient openaiWebClient;
    private final ObjectMapper objectMapper;

    @Autowired
    public OpenAIServiceImpl(WebClient openaiWebClient) {
        this.openaiWebClient = openaiWebClient;
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public Object handleChatCompletions(Map<String, Object> requestBody, Map<String, String> headers, boolean isStream) {
        try {
            String body = objectMapper.writeValueAsString(requestBody);
            String authHeader = headers.get(HttpHeaders.AUTHORIZATION);
            
            if (authHeader == null || authHeader.isEmpty()) {
                return Mono.error(new ApiKeyException("未提供OpenAI API密钥"));
            }
            
            return forwardRequest(ApiConstants.OPENAI_CHAT_COMPLETIONS_PATH, body, authHeader);
        } catch (JsonProcessingException e) {
            log.error("JSON处理错误", e);
            return Mono.error(e);
        }
    }
    
    @Override
    public boolean supportsModel(String modelName) {
        if (!StringUtils.hasLength(modelName)) {
            return false;
        }
        
        // 只检查模型前缀
        return modelName.startsWith("gpt-") || 
               modelName.startsWith("text-embedding") || 
               modelName.startsWith("openai/") ||
               modelName.startsWith("openai-");
    }

    /**
     * 转发请求到OpenAI API
     */
    public Mono<String> forwardRequest(String path, String body, String authHeader) {
        return openaiWebClient.post()
                .uri(path)
                .header(HttpHeaders.AUTHORIZATION, authHeader)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .bodyValue(body)
                .retrieve()
                .bodyToMono(String.class);
    }
} 